import sys
import os
import re

def is_valid_file(file_path, start_line, target_counts):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            lines = file.readlines()
            
            # 查找开始行的位置
            start_index = None
            for i, line in enumerate(lines):
                if line.strip().startswith(start_line):
                    start_index = i
                    break
            
            if start_index is None:
                print(f"Start line not found in file: {file_path}")
                return [0, False]
            
            # 从开始行之后查找 MAR 记录
            mar_count = 0
            for line in lines[start_index:]:
                if 'MAR' in line:
                    mar_count += 1
            
            valid = mar_count in target_counts
            return [mar_count, valid]
    
    except Exception as e:
        print(f"An error occurred: {e}")
        return [0, False]

def natural_sort_key(s):
    return [int(text) if text.isdigit() else text.lower() for text in re.split(r'(\d+)', s)]

def main():
    if len(sys.argv) != 3:
        print("Usage: python script.py <folder_path> <target_counts>")
        sys.exit(1)
    
    folder_path = sys.argv[1]
    target_counts_str = sys.argv[2]
    target_counts = list(map(int, target_counts_str.split(',')))
    
    # 检查 all_valid_files.txt 是否已经存在
    output_file_path = os.path.join(folder_path, 'all_valid_files.txt')
    if os.path.exists(output_file_path):
        print(f"File {output_file_path} already exists. Exiting.")
        sys.exit(0)
    
    results = []
    for root, dirs, files in os.walk(folder_path):
        for file_name in files:
            if file_name.endswith('.txt'):
                file_path = os.path.join(root, file_name)
                result = is_valid_file(file_path, "record# chan   nsync truetime/ns dtime", target_counts)
                results.append((file_name, result[0], result[1]))
    
    # 按自然排序方式排序
    results.sort(key=lambda x: natural_sort_key(x[0]))
    
    with open(output_file_path, 'w', encoding='utf-8') as output_file:
        for file_name, mar_count, valid in results:
            write_or_not = False
            for demand_count in target_counts:
                if write_or_not == False and mar_count == demand_count:
                    write_or_not = True
                    status = f"{mar_count} MAR records found" if valid else f"Invalid: {mar_count} MAR records found"
                    output_file.write(f"{file_name}: {status}\n")

if __name__ == "__main__":
    main()